package ro.k.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.k.jstore.LoginService;
import ro.k.web.beans.UserBean;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(description = "Used to authenticate a user", urlPatterns = { "/LoginServlet" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		throw new ServletException("Login servlet shold not be called get");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession sess = request.getSession();
		UserBean ub = (UserBean) sess.getAttribute(KConstants.UserKey);
		if (ub == null) {
			// TODO : validate account
			Object username = request.getParameter("uname");
			Object password = request.getParameter("upass");
			sess.setAttribute("loginError", null);
			LoginService.getInstance();
			if (LoginService.getInstance().validateUser(username.toString(),
					password.toString())) {
				ub = new UserBean(username.toString(), password.toString());
				sess.setAttribute(KConstants.UserKey, ub);
				response.sendRedirect("jsp/main.jsp");
				return;
			} else {
				sess.setAttribute("loginError", "error");
				response.sendRedirect("index.jsp");
				return;
			}
		} else {
			response.sendRedirect("jsp/main.jsp");
			return;
		}
	}

}
